<?php

namespace Wap\Controller;

use Think\Image;
use Think\Upload;
use User\Model\FactoryModel;
use User\Model\LpicModel;
use Wap\Service\WechatService;
use Wap\Service\WeixinService;

//header('Access-Control-Allow-Origin: *');

class LpicController extends WapController
{
    public $wxuser;//--活动绑定的微信号--
    public $lpic;//--直播活动配置--

    public function __construct()
    {
        parent::__construct();
        $this->handleCriteriaWxuser();
        if (empty($this->wxuser)) {
            header("Content-type: text/html; charset=utf-8");
            die("活动已失效！");
        }
        if (!headers_sent() && // 如果页面头部信息还没有输出--
            extension_loaded("zlib") && // 而且php已经加载了zlib扩展--
            strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")
        ) //而且浏览器接受GZIP--
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }

    }

    private function handleCriteriaWxuser()
    {
        $id = I('get.', '', '') ? I("get.id", -1, "") : I("post.id", -1, "");
        if (!empty($id)) {
            $cond_lpic['id'] = $id;
            $cond_lpic['status'] = LpicModel::STATUS_ACTIVE;
            $now_date = date("Y-m-d H:i:s");
            $cond_lpic['start_date'] = array("LT", $now_date);
            $cond_lpic['end_date'] = array("GT", $now_date);
            $this->lpic = M("live_pic")->where($cond_lpic)->find();
            if (empty($this->lpic)) {
                return false;
            }
            $this->wxuser = S('live_pic_wxuser_' . $id);
            if (!empty($this->wxuser)) {
                $this->wxuser = S('live_pic_wxuser_' . $id);
                return true;
            }
            $this->wxuser = WeixinService::getWxuser($this->lpic['token']);
            if (empty($this->wxuser)) {
                return false;
            }
            S('live_pic_wxuser_' . $id, $this->wxuser);
            return true;
        } else {
            return false;
        }
    }

    private function handleCriteriaURL()
    {
        $id = I("get.id", -1, "");
        $openid = session('session_live_openid_' . $id);
        if (empty($openid)) {
            if (!isset($_GET['code'])) {
                $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $wechat = new WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                $url = $wechat->snsapiUserInfoLink($url, $this->wxuser['appid']);
                header("Location: " . $url);
                exit();
            } else {
                $wechat = new WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                $out = $wechat->snsapiUserInfo($this->wxuser['appid'], $this->wxuser['appsecret'], $_GET['code']);
                if ($out != null) {
                    session('session_live_openid_' . $id, $out['openid']);
                    /*session('session_live_wxname_' . $id, $out['nickname']);
                    session('session_live_wximg_' . $id, $out['headimgurl']);*/
                }
            }
        }
    }

    public function index()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            //--非微信浏览器--
        } else {
            $is_wx = true;
//            $this->handleCriteriaURL();
        }
        $this->assign("title", $this->lpic['name']);
        $this->assign("color", $this->lpic['color']);
        return $this->display();
    }

    //---首页起始加载直播活动数据详情--
    public function ajaxIndex()
    {
        $url = I('get.url', "");
        $lpic = array();
        $lpic = $this->lpic;
        $menu_list = array();
        $wxConfig = array();
        $item_list = array();
        $cond_item['live_id'] = $lpic['id'];
        $cond_item['status'] = LpicModel::STATUS_ACTIVE;
        $item_list = M("live_pic_item")->where($cond_item)->field("item_id, describe, name, priority, type")->order("priority asc")->limit(3)->select();
        foreach ($item_list as &$item) {
            $cond_item_pic['item_id'] = $item['item_id'];
            $cond_item_pic['status'] = LpicModel::STATUS_ACTIVE;
            $pic_list = M("live_pic_pic")->where($cond_item_pic)->order("priority asc")->select();
            $item['pic_list'] = $pic_list;
        }

        $cond_menu = $cond_item;
        $menu_list = M("live_pic_menu")->where($cond_menu)->field("menu_id, content, icon")->order("priority asc")->select();

        $wxConfig = array(
            'appId' => '',
            'nonceStr' => '',
            'timestamp' => '',
            'signature' => ''
        );
        $wx = WeixinService::getWxuser($this->wxuser['token']);
        $wxJSApi = WeixinService::buildWXJSApi($wx, $url);
        if (!empty($wxJSApi)) {
            $wxConfig = array(
                'appId' => $wx['appid'],
                'nonceStr' => $wxJSApi['noncestr'],
                'timestamp' => $wxJSApi['timestamp'],
                'signature' => $wxJSApi['sha1']
            );
        }
        $wxConfig['share_title'] = $this->lpic['share_title'];
        $wxConfig['share_desc'] = $this->lpic['share_desc'];
        $wxConfig['share_pic'] = $this->lpic['share_pic'];
        $wxConfig['share_url'] = $this->lpic['share_url'];
        $this->ajaxReturn(["res" => 1, "lpic" => $lpic, "item_list" => $item_list, "menu_list" => $menu_list, "wxConfig" => $wxConfig]);
    }

    //--分页加载数据详情--
    public function ajaxPicpage()
    {
        $item_list = array();
        $item_lists = array();
        $page_num = 3;
        $page = I("get.page", 0, "");
        $type = I("get.type", 0, "");//--0:专题模式，1：时间轴模式--
        $priority_type = I("get.priority_type", 0, "");//---0：不切换，1：切换--
        $lpic = $this->lpic;
        $cond_item['live_id'] = $lpic['id'];
        $cond_item['status'] = LpicModel::STATUS_ACTIVE;
        if ($type == 0) {//--专题模式---
            $order = $priority_type ? "priority desc" : "priority asc";
            $item_lists = M("live_pic_item")->where($cond_item)
                ->field("item_id, describe, name, priority, type")->order($order)->limit($page * $page_num, $page_num)->select();
            foreach ($item_lists as &$item) {
                $cond_item_pic['item_id'] = $item['item_id'];
                $cond_item_pic['status'] = LpicModel::STATUS_ACTIVE;
                $pic_list = M("live_pic_pic")->where($cond_item_pic)->order("priority asc")->select();
                $item['pic_list'] = $pic_list;
            }
        } else {
            $field = $lpic['t_order_type'] ? "hour" : "day";
            $order = '';
            if ($priority_type == 0) {
                $order = $lpic['pic_order'] ? $field . " asc" : $field . " desc";
            } else {
                $order = $lpic['pic_order'] ? $field . " desc" : $field . " asc";
            }
            $cond_pic['live_id'] = $lpic['id'];
            $cond_pic['status'] = LpicModel::STATUS_ACTIVE;
            $time_list = M("live_pic_pic")->group($order)->where($cond_pic)->field("hour, day")->limit($page * $page_num, $page_num)->select();

            foreach ($time_list as $time) {
                $cond_pic[$field] = $time[$field];
                $pic_list = M("live_pic_pic")->where($cond_pic)->select();
                $time_name = ($field === "day") ? $time[$field] : $time[$field] . ":00:00";
                $item = [
                    'name' => $time_name,
                    'pic_list' => $pic_list
                ];
                if (array_key_exists($time['day'], $item_lists)) {
                    $item_lists[$time['day']][] = $item;
                } else {
                    $item_lists[$time['day']] = array($item);
                }
            }
            $item_lists_new = array();
            foreach ($item_lists as $key => $val) {
                $item_lists_new[] = [
                    'day' => $key,
                    'times' => $val
                ];
            }
            $item_lists = $item_lists_new;
        }
        $this->ajaxReturn(["res" => 1, "item_list" => $item_lists, 'type' => $type]);
    }

    public function login()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            //--非微信浏览器--
        } else {
            $is_wx = true;
            //$this->handleCriteriaURL();
        }
        $this->assign("color", $this->lpic['color']);
        return $this->display();
    }

    //--请求用户状态--
    public function ajaxLoginIndex()
    {
        //--判断登陆状态--
        $phone = session("login_phone");
        if (empty($phone)) {
            $this->ajaxReturn(array("res" => -1, "result" => "用户未登陆"));
        } else {
            $cond['phone'] = $phone;
            $cond['status'] = array("NEQ", LpicModel::STATUS_DELETE);
            $cond['id'] = I("get.id", "", "");
            $user = M("live_pic_user")->where($cond)->field("status as user_status,result")->find();
            if (empty($user)) {
                $this->ajaxReturn(array("res" => -1, "result" => "用户未登陆"));
            }
            $user['show_describe'] = $this->lpic['show_detail'] % 10;
            $user['color'] = $this->lpic['color'];
            $this->ajaxReturn(array("res" => 1, "result" => $user));
        }
    }

    //---登陆--
    public function ajaxLogin()
    {
        $params = I("get.", "", "");
        if (empty($params['phone'])) {
            $this->ajaxReturn(array("res" => -1, "result" => "请填写手机号码"));
        }
        $cond['phone'] = $params['phone'];
        $cond['status'] = array("NEQ", LpicModel::STATUS_DELETE);
        $cond['id'] = $params['id'];
        $user = M("live_pic_user")->where($cond)->find();
        if (empty($user)) {
            $this->ajaxReturn(array("res" => -1, "result" => "登录失败，请检查手机号码/短信验证码"));
        }
        if (empty($params['sms'])) {
            $this->ajaxReturn(array("res" => -2, "result" => "短信验证码不正确"));
        }
        $sms = session("lpic_sms");
        if ($sms != strtoupper($params['sms'])) {
            $this->ajaxReturn(array("res" => -2, "result" => "短信验证码不正确!" . $sms . "|" . $params['sms']));
        }
        session("login_phone", $params['phone']);
        $result['user_status'] = $user['status'];
        $result['result'] = $user['result'];
        $lpic = $this->lpic;
        $result['show_describe'] = $lpic['show_detail'] % 10;//---0:不需要描述,1:需要描述--
        $result['color'] = $lpic['color'];
        $this->ajaxReturn(array('res' => 1, "result" => $result));
    }

    //--获取短信验证码----
    public function ajaxGetSms()
    {
        $phone = I("get.phone", "", "");
        if (empty($phone)) {
            $this->ajaxReturn(array('res' => -1, 'result' => "请填写电话号码"));
        }
        $session_time = session("mt_time");
        if ($session_time != null && ($session_time + 29) > time()) {
            $this->ajaxReturn(array("res" => -2, "result" => "请求验证码太频繁"));
        }
        session("mt_time", time());
        $cond['phone'] = $phone;
        $cond['status'] = array("NEQ", LpicModel::STATUS_DELETE);
        $cond['id'] = $this->lpic['id'];
        $user = M("live_pic_user")->where($cond)->find();
        if (empty($user)) {
            $this->ajaxReturn(array("res" => -3, "result" => "此号码未注册"));
        }

        $authcode = '';
        for ($i = 0; $i < 4; $i++) {
            $randAsciiNum = rand(48, 57);
            $randStr = chr($randAsciiNum);
            $authcode .= $randStr;
        }
        $msg = "您的验证码为：" . $authcode;
        session("lpic_sms", $authcode);
        $result = FactoryModel::sendMsg($phone, $msg);
        $this->ajaxReturn(array('res' => 1, 'result' => "成功"));
//        $this->ajaxReturn(array('res' => 1, 'result' => $msg));
    }

    //--注册----
    public function ajaxRegister()
    {
        $params = I("get.", "", "");
        if (empty($params['phone'])) {
            $this->ajaxReturn(array("res" => -1, "result" => "请填写手机号码"));
        }
        $cond['phone'] = $params['phone'];
        $cond['status'] = array("NEQ", LpicModel::STATUS_DELETE);
        $cond['id'] = $params['id'];
        $count = M('live_pic_user')->where($cond)->count();
        if ($count) {
            $this->ajaxReturn(array("res" => -2, "result" => "此号码已经被注册"));
        }
        $data['live_id'] = $params['id'];
        $data['name'] = $params['name'];
        $data['phone'] = $params['phone'];
        $data['company'] = $params['company'];
        $data['nickname'] = $params['nickname'];
        M("live_pic_user")->add($data);
        $this->ajaxReturn(array('res' => 1, 'result' => "成功"));
    }

    //--注册用户上传图片信息--
    public function ajaxUpload()
    {
        //--判断登陆状态--
//        $phone = '15869022160';
        $phone = session("login_phone");
        if (empty($phone)) {
            $this->ajaxReturn(array('status' => -1, 'result' => "请先登陆"));
        }
        $cond_user['live_id'] = I("post.id", "", "");
        $cond_user['status'] = LpicModel::STATUS_ACTIVE;
        $cond_user['phone'] = $phone;
        $user = M("live_pic_user")->where($cond_user)->find();
        if (empty($user) || ($user['status'] != LpicModel::STATUS_ACTIVE)) {
            $this->ajaxReturn(array('res' => -1, 'result' => "用户状态异常"));
        }
        $upload = new Upload();// 实例化上传类
        $upload->maxSize = 7123456;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/lpic/'; // 设置附件上传根目录
        $upload->subName = array("date", "Ymd");
        $upload->saveName = array("uniqid", "lpic");
        // 上传文件
        $group_id = $data['group_id'] = I("post.group_id", "", "");
        $info = $upload->upload();
        if (!$info) {
            if (!empty($data['group_id'])) {
                $cond_del['group_id'] = $data['group_id'];
                $cond_del['live_id'] = I("post.id", "", "");
                $data_del['status'] = LpicModel::STATUS_DELETE;
                M("live_pic_pic")->where($cond_del)->save($data_del);
            }

            $this->ajaxReturn(array('res' => -2, 'result' => $upload->getError()));
        }
        $data_save_path = '';
        $file_name = "";
        $pic_url = "";
        foreach ($info as $file) {
            $pic_url = "Public/Uploads/lpic/" . date('Ymd') . "/" . $file['savename'];
            $file_name = $file['savename'];
            $data_save_path .= "http://" . $_SERVER["HTTP_HOST"] . '/Public/Uploads/lpic/' . date('Ymd') . "/" . $file['savename'];
        }
        $image = new \Think\Image();
        $image->open($pic_url);
        $width = $image->width(); // 返回图片的宽度
        $height = $image->height(); // 返回图片的宽度
        $thumb_w = 750;
        $thumb_h = ceil($height / $width) * $height;
        $rename_mid = 'Public/Uploads/lpic/' . date('Ymd') . "/mid" . $file_name;
        $image->thumb($thumb_w, $thumb_h)->save($rename_mid);

        $image->open($pic_url);
        $width = $image->width(); // 返回图片的宽度
        $height = $image->height(); // 返回图片的宽度
        $thumb_w = 200;
        $thumb_h = ceil($height / $width) * $height;
        $rename_min = 'Public/Uploads/lpic/' . date('Ymd') . "/min" . $file_name;
        $image->thumb($thumb_w, $thumb_h)->save($rename_min);
        $data['group_id'] =
        $data['live_id'] = I("post.id", "", "");
        $data['pic_url'] = $data_save_path;
        list($width, $height, $type, $attr) = getimagesize($data['pic_url']);
        $data['pic_url'] .= "?w=" . $width . "&h=" . $height;
        $data['author'] = $user['name'];
        $data['nickname'] = $user['nickname'];
        $data['describe'] = I("post.describe", "", "");
        $lpic = $this->lpic;
        if ($lpic['pic_check']) {
            $data['status'] = LpicModel::STATUS_PENDING;
        } else {
            $data['status'] = LpicModel::STATUS_ACTIVE;
        }
        $data['pic_url_min'] = "http://" . $_SERVER['HTTP_HOST'] . "/" . $rename_min;
        list($width, $height, $type, $attr) = getimagesize($data['pic_url_min']);
        $data['pic_url_min'] .= "?w=" . $width . "&h=" . $height;
        $data['pic_url_mid'] = "http://" . $_SERVER['HTTP_HOST'] . "/" . $rename_mid;
        list($width, $height, $type, $attr) = getimagesize($data['pic_url_mid']);
        $data['pic_url_mid'] .= "?w=" . $width . "&h=" . $height;
        $data['day'] = date("Y-m-d");
        $data['hour'] = date("Y-m-d H");
        if (empty($group_id)) {
            $cond_max['live_id'] = I("post.id", "", "");
            $max_group_id = M("live_pic_pic")->where($cond_max)->max("group_id");
            $group_id = $data['group_id'] = $max_group_id + 1;
        }
        M("live_pic_pic")->add($data);
        $this->ajaxReturn(array('res' => 1, 'result' => "成功", "group_id" => $group_id));
    }

    public function ajaxLoginOut()
    {
        $phone = session("login_phone");
        if (!empty($phone)) {
            session("login_phone", null);
        }
        $this->ajaxReturn(array('res' => 1, 'result' => "成功"));
    }
}
